home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / ROLE.PY < prev    next >
Encoding:
Python Source  |  2000-09-01  |  21.7 KB  |  605 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. """Access control support"""
  65.  
  66. __version__='$Revision: 1.37.18.3 $'[11:-2]
  67.  
  68.  
  69. from Globals import HTMLFile, MessageDialog, Dictionary
  70. from string import join, strip, split, find
  71. from Acquisition import Implicit, Acquired, aq_get
  72. import Globals, ExtensionClass, PermissionMapping, Products
  73. from Permission import Permission
  74. from App.Common import aq_base
  75.  
  76. ListType=type([])
  77.  
  78. def _isBeingUsedAsAMethod(self):
  79.     return aq_get(self, '_isBeingUsedAsAMethod_', 0)
  80.  
  81. def _isNotBeingUsedAsAMethod(self):
  82.     return not aq_get(self, '_isBeingUsedAsAMethod_', 0)
  83.  
  84. class RoleManager(ExtensionClass.Base, PermissionMapping.RoleManager):
  85.     """An obect that has configurable permissions"""
  86.  
  87.     __ac_permissions__=(
  88.         ('Change permissions',
  89.          ('manage_access', 'permission_settings',
  90.           'ac_inherited_permissions',
  91.           'manage_roleForm', 'manage_role',
  92.           'manage_acquiredForm', 'manage_acquiredPermissions',
  93.           'manage_permissionForm', 'manage_permission',
  94.           'manage_changePermissions', 'permissionsOfRole',
  95.           'rolesOfPermission', 'acquiredRolesAreUsedBy',
  96.           'manage_defined_roles', 'userdefined_roles',
  97.           'manage_listLocalRoles', 'manage_editLocalRoles',
  98.           'manage_setLocalRoles', 'manage_addLocalRoles',
  99.           'manage_delLocalRoles',
  100.           )),
  101.         )
  102.  
  103.     manage_options=(
  104.         {'label':'Security', 'action':'manage_access',
  105.          'help':('OFSP','Security.stx'),
  106.          'filter': _isNotBeingUsedAsAMethod,
  107.          },
  108.         {'label':'Define Permissions', 'action':'manage_access',
  109.          'help':('OFSP','Security_Define-Permissions.stx'),
  110.          'filter': _isBeingUsedAsAMethod,
  111.          },
  112.         )
  113.    
  114.     __ac_roles__=('Manager', 'Owner', 'Anonymous')
  115.  
  116.     permissionMappingPossibleValues=Acquired
  117.  
  118.     #------------------------------------------------------------
  119.  
  120.     def ac_inherited_permissions(self, all=0):
  121.         # Get all permissions not defined in ourself that are inherited
  122.         # This will be a sequence of tuples with a name as the first item and
  123.         # an empty tuple as the second.
  124.         d={}
  125.         perms=self.__ac_permissions__
  126.         for p in perms: d[p[0]]=None
  127.             
  128.         r=gather_permissions(self.__class__, [], d)
  129.         if all:
  130.            if hasattr(self, '_subobject_permissions'):
  131.                for p in self._subobject_permissions():
  132.                    pname=p[0]
  133.                    if not d.has_key(pname):
  134.                        d[pname]=1
  135.                        r.append(p)
  136.             
  137.            r=list(perms)+r
  138.            r.sort()
  139.             
  140.         return tuple(r)
  141.  
  142.     def permission_settings(self):
  143.         """Return user-role permission settings
  144.         """
  145.         result=[]
  146.         valid=self.valid_roles()
  147.         indexes=range(len(valid))
  148.         ip=0
  149.         for p in self.ac_inherited_permissions(1):
  150.             name, value = p[:2]
  151.             p=Permission(name,value,self)
  152.             roles=p.getRoles()
  153.             d={'name': name,
  154.                'acquire': type(roles) is ListType and 'CHECKED' or '',
  155.                'roles': map(
  156.                    lambda ir, roles=roles, valid=valid, ip=ip:
  157.                    {
  158.                        'name': "p%dr%d" % (ip,ir),
  159.                        'checked': (valid[ir] in roles) and 'CHECKED' or '',
  160.                        },
  161.                    indexes)
  162.                }
  163.             ip=ip+1
  164.             result.append(d)
  165.  
  166.         return result
  167.  
  168.     manage_roleForm=HTMLFile('roleEdit', globals(), management_view='Security',
  169.                              help_topic='Security_Manage-Role.stx',
  170.                              help_product='OFSP')
  171.  
  172.     def manage_role(self, role_to_manage, permissions=[], REQUEST=None):
  173.         "Change the permissions given to the given role"
  174.         self._isBeingUsedAsAMethod(REQUEST, 0)
  175.         for p in self.ac_inherited_permissions(1):
  176.             name, value = p[:2]
  177.             p=Permission(name,value,self)
  178.             p.setRole(role_to_manage, name in permissions)
  179.  
  180.         if REQUEST is not None: return self.manage_access(self,REQUEST)
  181.  
  182.     manage_acquiredForm=HTMLFile('acquiredEdit', globals(), management_view='Security',
  183.                                  help_topic='Security_Manage-Acquisition.stx',
  184.                                  help_product='OFSP')
  185.  
  186.     def manage_acquiredPermissions(self, permissions=[], REQUEST=None):
  187.         "Change the permissions that acquire"
  188.         self._isBeingUsedAsAMethod(REQUEST, 0)
  189.         for p in self.ac_inherited_permissions(1):
  190.             name, value = p[:2]
  191.             p=Permission(name,value,self)
  192.             roles=p.getRoles()
  193.             if roles is None: continue
  194.             if name in permissions: p.setRoles(list(roles))
  195.             else:                   p.setRoles(tuple(roles))
  196.  
  197.         if REQUEST is not None: return self.manage_access(self,REQUEST)
  198.         
  199.     manage_permissionForm=HTMLFile('permissionEdit', globals(), management_view='Security',
  200.                                    help_topic='Security_Manage-Permission.stx',
  201.                                    help_product='OFSP')
  202.     
  203.     def manage_permission(self, permission_to_manage,
  204.                           roles=[], acquire=0, REQUEST=None):
  205.         """Change the settings for the given permission
  206.  
  207.         If optional arg acquire is true, then the roles for the permission
  208.         are acquired, in addition to the ones specified, otherwise the
  209.         permissions are restricted to only the designated roles."""
  210.         self._isBeingUsedAsAMethod(REQUEST, 0)
  211.         for p in self.ac_inherited_permissions(1):
  212.             name, value = p[:2]
  213.             if name==permission_to_manage:
  214.                 p=Permission(name,value,self)
  215.                 if acquire: roles=list(roles)
  216.                 else: roles=tuple(roles)
  217.                 p.setRoles(roles)
  218.                 if REQUEST is not None: return self.manage_access(self,REQUEST)
  219.                 return
  220.  
  221.         raise 'Invalid Permission', (
  222.             "The permission <em>%s</em> is invalid." % permission_to_manage)
  223.         
  224.     
  225.     def manage_access(
  226.         trueself, self, REQUEST,
  227.         _normal_manage_access=HTMLFile('access', globals()),
  228.         _method_manage_access=HTMLFile('methodAccess', globals()),
  229.         **kw):
  230.         "Return an interface for making permissions settings"
  231.         if self._isBeingUsedAsAMethod():
  232.             return apply(_method_manage_access,(trueself, self, REQUEST), kw)
  233.         else:
  234.             return apply(_normal_manage_access,(trueself, self, REQUEST), kw)
  235.     
  236.     def manage_changePermissions(self, REQUEST):
  237.         "Change all permissions settings, called by management screen"
  238.         self._isBeingUsedAsAMethod(REQUEST, 0)
  239.         valid_roles=self.valid_roles()
  240.         indexes=range(len(valid_roles))
  241.         have=REQUEST.has_key
  242.         permissions=self.ac_inherited_permissions(1)
  243.         for ip in range(len(permissions)):
  244.             roles=[]
  245.             for ir in indexes:
  246.                 if have("p%dr%d" % (ip,ir)): roles.append(valid_roles[ir])
  247.             name, value = permissions[ip][:2]
  248.             p=Permission(name,value,self)
  249.             if not have('a%d' % ip): roles=tuple(roles)
  250.             p.setRoles(roles)
  251.  
  252.         return MessageDialog(
  253.             title  ='Success!',
  254.             message='Your changes have been saved',
  255.             action ='manage_access')
  256.  
  257.  
  258.     def permissionsOfRole(self, role):
  259.         "used by management screen"
  260.         r=[]
  261.         for p in self.ac_inherited_permissions(1):
  262.             name, value = p[:2]
  263.             p=Permission(name,value,self)
  264.             roles=p.getRoles()
  265.             r.append({'name': name,
  266.                       'selected': role in roles and 'SELECTED' or '',
  267.                       })
  268.         return r
  269.  
  270.     def rolesOfPermission(self, permission):
  271.         "used by management screen"
  272.         valid_roles=self.valid_roles()
  273.         for p in self.ac_inherited_permissions(1):
  274.             name, value = p[:2]
  275.             if name==permission:
  276.                 p=Permission(name,value,self)
  277.                 roles=p.getRoles()
  278.                 return map(
  279.                     lambda role, roles=roles:
  280.                     {'name': role,
  281.                      'selected': role in roles and 'SELECTED' or '',
  282.                      },
  283.                     valid_roles)
  284.         
  285.         raise 'Invalid Permission', (
  286.             "The permission <em>%s</em> is invalid." % permission)
  287.  
  288.     def acquiredRolesAreUsedBy(self, permission):
  289.         "used by management screen"
  290.         for p in self.ac_inherited_permissions(1):
  291.             name, value = p[:2]
  292.             if name==permission:
  293.                 p=Permission(name,value,self)
  294.                 roles=p.getRoles()
  295.                 return type(roles) is ListType and 'CHECKED' or ''
  296.         
  297.         raise 'Invalid Permission', (
  298.             "The permission <em>%s</em> is invalid." % permission)
  299.  
  300.  
  301.     # Local roles support
  302.     # -------------------
  303.     #
  304.     # Local roles allow a user to be given extra roles in the context
  305.     # of a particular object (and its children). When a user is given
  306.     # extra roles in a particular object, an entry for that user is made
  307.     # in the __ac_local_roles__ dict containing the extra roles.
  308.     
  309.     __ac_local_roles__=None
  310.  
  311.     manage_listLocalRoles=HTMLFile('listLocalRoles', globals(), management_view='Security',
  312.                                    help_topic='Security_Local-Roles.stx',
  313.                                    help_product='OFSP')
  314.  
  315.     manage_editLocalRoles=HTMLFile('editLocalRoles', globals(), management_view='Security',
  316.                                    help_topic='Security_User-Local-Roles.stx',
  317.                                    help_product='OFSP')
  318.  
  319.     def has_local_roles(self):
  320.         dict=self.__ac_local_roles__ or {}
  321.         return len(dict)
  322.  
  323.     def get_local_roles(self):
  324.         dict=self.__ac_local_roles__ or {}
  325.         keys=dict.keys()
  326.         keys.sort()
  327.         info=[]
  328.         for key in keys:
  329.             value=tuple(dict[key])
  330.             info.append((key, value))
  331.         return tuple(info)
  332.  
  333.     def get_valid_userids(self):
  334.         item=self
  335.         dict={}
  336.         while 1:
  337.             if hasattr(aq_base(item), 'acl_users') and \
  338.                hasattr(item.acl_users, 'user_names'):
  339.                 for name in item.acl_users.user_names():
  340.                     dict[name]=1
  341.             if not hasattr(item, 'aq_parent'):
  342.                 break
  343.             item=item.aq_parent
  344.         keys=dict.keys()
  345.         keys.sort()
  346.         return tuple(keys)
  347.  
  348.     def get_local_roles_for_userid(self, userid):
  349.         dict=self.__ac_local_roles__ or {}
  350.         return tuple(dict.get(userid, []))
  351.  
  352.     def manage_addLocalRoles(self, userid, roles, REQUEST=None):
  353.         """Set local roles for a user."""
  354.         if not roles:
  355.             raise ValueError, 'One or more roles must be given!'
  356.         dict=self.__ac_local_roles__ or {}
  357.         local_roles = list(dict.get(userid, []))
  358.         for r in roles:
  359.             if r not in local_roles:
  360.                 local_roles.append(r)
  361.         dict[userid] = local_roles
  362.         self.__ac_local_roles__=dict
  363.         if REQUEST is not None:
  364.             stat='Your changes have been saved.'
  365.             return self.manage_listLocalRoles(self, REQUEST, stat=stat)
  366.  
  367.     def manage_setLocalRoles(self, userid, roles, REQUEST=None):
  368.         """Set local roles for a user."""
  369.         if not roles:
  370.             raise ValueError, 'One or more roles must be given!'
  371.         dict=self.__ac_local_roles__ or {}
  372.         dict[userid]=roles
  373.         self.__ac_local_roles__=dict
  374.         if REQUEST is not None:
  375.             stat='Your changes have been saved.'
  376.             return self.manage_listLocalRoles(self, REQUEST, stat=stat)
  377.  
  378.     def manage_delLocalRoles(self, userids, REQUEST=None):
  379.         """Remove all local roles for a user."""
  380.         dict=self.__ac_local_roles__ or {}
  381.         for userid in userids:
  382.             if dict.has_key(userid):
  383.                 del dict[userid]
  384.         self.__ac_local_roles__=dict
  385.         if REQUEST is not None:
  386.             stat='Your changes have been saved.'
  387.             return self.manage_listLocalRoles(self, REQUEST, stat=stat)
  388.  
  389.  
  390.  
  391.  
  392.     #------------------------------------------------------------
  393.  
  394.     access_debug_info__roles__=()
  395.     def access_debug_info(self):
  396.         "Return debug info"
  397.         clas=class_attrs(self)
  398.         inst=instance_attrs(self)
  399.         data=[]
  400.         _add=data.append
  401.         for key, value in inst.items():
  402.             if find(key,'__roles__') >= 0:
  403.                 _add({'name': key, 'value': value, 'class': 0})
  404.             if hasattr(value, '__roles__'):
  405.                 _add({'name': '%s.__roles__' % key, 'value': value.__roles__, 
  406.                       'class': 0})
  407.         for key, value in clas.items():
  408.             if find(key,'__roles__') >= 0:
  409.                 _add({'name': key, 'value': value, 'class' : 1})
  410.             if hasattr(value, '__roles__'):
  411.                 _add({'name': '%s.__roles__' % key, 'value': value.__roles__, 
  412.                       'class': 1})
  413.         return data
  414.  
  415.     def valid_roles(self):
  416.         "Return list of valid roles"
  417.         obj=self
  418.         dict={}
  419.         dup =dict.has_key
  420.         x=0
  421.         while x < 100:
  422.             if hasattr(obj, '__ac_roles__'):
  423.                 roles=obj.__ac_roles__
  424.                 for role in roles:
  425.                     if not dup(role):
  426.                         dict[role]=1
  427.             if not hasattr(obj, 'aq_parent'):
  428.                 break
  429.             obj=obj.aq_parent
  430.             x=x+1
  431.         roles=dict.keys()
  432.         roles.sort()
  433.         return tuple(roles)
  434.  
  435.     def validate_roles(self, roles):
  436.         "Return true if all given roles are valid"
  437.         valid=self.valid_roles()
  438.         for role in roles:
  439.             if role not in valid:
  440.                 return 0
  441.         return 1
  442.  
  443.     def userdefined_roles(self):
  444.         "Return list of user-defined roles"
  445.         roles=list(self.__ac_roles__)
  446.         for role in classattr(self.__class__,'__ac_roles__'):
  447.             try:    roles.remove(role)
  448.             except: pass
  449.         return tuple(roles)
  450.  
  451.  
  452.     def manage_defined_roles(self,submit=None,REQUEST=None):
  453.         """Called by management screen."""
  454.  
  455.         if submit=='Add Role':
  456.             role=reqattr(REQUEST, 'role')
  457.             return self._addRole(role, REQUEST)
  458.  
  459.         if submit=='Delete Role':
  460.             roles=reqattr(REQUEST, 'roles')
  461.             return self._delRoles(roles, REQUEST)
  462.  
  463.         return self.manage_access(self,REQUEST)
  464.  
  465.     def _addRole(self, role, REQUEST=None):
  466.         if not role:
  467.             return MessageDialog(
  468.                    title  ='Incomplete',
  469.                    message='You must specify a role name',
  470.                    action ='manage_changeAccess')
  471.         if role in self.__ac_roles__:
  472.             return MessageDialog(
  473.                    title  ='Role Exists',
  474.                    message='The given role is already defined',
  475.                    action ='manage_changeAccess')
  476.         data=list(self.__ac_roles__)
  477.         data.append(role)
  478.         self.__ac_roles__=tuple(data)
  479.         if REQUEST is not None:
  480.             return self.manage_access(self, REQUEST)
  481.  
  482.  
  483.     def _delRoles(self, roles, REQUEST):
  484.         if not roles:
  485.             return MessageDialog(
  486.                    title  ='Incomplete',
  487.                    message='You must specify a role name',
  488.                    action ='manage_changeAccess')
  489.         data=list(self.__ac_roles__)
  490.         for role in roles:
  491.             try:    data.remove(role)
  492.             except: pass
  493.         self.__ac_roles__=tuple(data)
  494.         if REQUEST is not None:
  495.             return self.manage_access(self, REQUEST)
  496.  
  497.  
  498.     def _has_user_defined_role(self, role):
  499.         return role in self.__ac_roles__
  500.         
  501.  
  502.     # Compatibility names only!!
  503.  
  504.     smallRolesWidget=selectedRoles=aclAChecked=aclPChecked=aclEChecked=''
  505.     validRoles=valid_roles
  506.     #manage_rolesForm=manage_access
  507.  
  508.     def manage_editRoles(self,REQUEST,acl_type='A',acl_roles=[]):
  509.         pass
  510.  
  511.     def _setRoles(self,acl_type,acl_roles):
  512.         pass
  513.  
  514.     def possible_permissions(self):
  515.         d={}
  516.         for p in Products.__ac_permissions__:
  517.             d[p[0]]=1
  518.         for p in self.aq_acquire('_getProductRegistryData')('ac_permissions'):
  519.             d[p[0]]=1
  520.  
  521.         for p in self.ac_inherited_permissions(1):
  522.             d[p[0]]=1
  523.  
  524.         d=d.keys()
  525.         d.sort()
  526.         
  527.         return d
  528.  
  529.  
  530. Globals.default__class_init__(RoleManager)
  531.  
  532.  
  533. def reqattr(request, attr):
  534.     try:    return request[attr]
  535.     except: return None
  536.  
  537. def classattr(cls, attr):
  538.     if hasattr(cls, attr):
  539.         return getattr(cls, attr)
  540.     try:    bases=cls.__bases__
  541.     except: bases=()
  542.     for base in bases:
  543.         if classattr(base, attr):
  544.             return attr
  545.     return None
  546.  
  547. def instance_dict(inst):
  548.     try:    return inst.__dict__
  549.     except: return {}
  550.  
  551. def class_dict(_class):
  552.     try:    return _class.__dict__
  553.     except: return {}
  554.  
  555. def instance_attrs(inst):
  556.     return instance_dict(inst)
  557.  
  558. def class_attrs(inst, _class=None, data=None):
  559.     if _class is None:
  560.         _class=inst.__class__
  561.         data={}
  562.  
  563.     clas_dict=class_dict(_class)
  564.     inst_dict=instance_dict(inst)
  565.     inst_attr=inst_dict.has_key
  566.     for key, value in clas_dict.items():
  567.         if not inst_attr(key):
  568.             data[key]=value
  569.     for base in _class.__bases__:
  570.         data=class_attrs(inst, base, data)
  571.     return data
  572.  
  573. def gather_permissions(klass, result, seen):
  574.     for base in klass.__bases__:
  575.         if base.__dict__.has_key('__ac_permissions__'):
  576.             for p in base.__ac_permissions__:
  577.                 name=p[0]
  578.                 if seen.has_key(name): continue
  579.                 result.append((name, ()))
  580.                 seen[name]=None
  581.         gather_permissions(base, result, seen)
  582.     return result
  583.  
  584.